package com.shimao.celnet.payment.controller.api;


import com.shimao.celnet.payment.config.ConstantConfig;
import com.shimao.celnet.payment.model.PPay;
import com.shimao.celnet.payment.model.PPayCust;
import com.shimao.celnet.payment.model.request.CallOut_allinPayRequest;
import com.shimao.celnet.payment.service.PPayCupUserService;
import com.shimao.celnet.payment.service.PPayCustService;
import com.shimao.celnet.payment.service.PPayService;
import com.shimao.celnet.payment.service.SCodeNameService;
import com.shimao.celnet.payment.service.impl.apiservice.CallOut_TLPublicService;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

/*
 * 功能描述: 通联对接more+支付接口
 * @Author: Matt
 * @Date: 2019/5/20 16:16
 */

@RestController
@RequestMapping(value = "/allin")
public class CallOut_allinPayController {
    protected Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private PPayService pPayService;

    @Autowired
    private PPayCustService pPayCustService;

    @Autowired
    private ConstantConfig constantConfig;

    @Autowired
    private CallOut_TLPublicService callOut_tlPublicService;

    @Autowired
    private SCodeNameService sCodeNameService;

    @Autowired
    private PPayCupUserService pPayCupUserService;

    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    public Object payToTL(@RequestBody CallOut_allinPayRequest form) throws Exception {
        logger.info("请求开始------------------");
        if (form.getPaymentId() != null && form.getPaymentId() !=""){
            String TimeStamp = String.valueOf(System.currentTimeMillis());//时间戳，用于商户交易订单号
            //根据guid查询数据库中的账单表
            PPay pPay = pPayService.getByKey(form.getPaymentId());
            logger.info(pPay+"支付信息----------------------");
            //根据小区sfid获取商户信息
            PPayCust pPayCust = getTLMessage(pPay.getEstateGuid(),form.getpType());
            logger.info(pPayCust.getCustId()+"商户Id----------------------");
            if ("W01".equals(form.getpType())){      //微信主扫
                logger.info("****************微信主扫******************");
                String BusinessType =  sCodeNameService.getNameByCode(pPay.getBusinessType());
                if(BusinessType==null||BusinessType==""){
                    BusinessType = pPay.getBusinessType();
                }
                //请求通联callout
                logger.info("***************************请求通联微信支付："+pPay.getPayAmount()+"*******>>>>>pPayCust："+pPayCust.getCustId());
                Map<String, String> map = callOut_tlPublicService.payGroup(pPay.getPayAmount(), TimeStamp, form.getpType(), BusinessType, pPay.getPayRemark(), "000000", constantConfig.getTlReturnURLMOREPLUS(),pPayCust);
                logger.info("***************************通联微信主扫响应参数："+map.toString());
                //   Map<String, String> map = service.pay("1", TimeStamp, pType,pPay.getBusinessType(), pPay.getPayRemark(), "000000", FinalUtil.TL_RETURN_URL);
                //支付成功更新账单retcode：SUCCESS 请求成功 trxstatus：0000 拿到支付链接
                if ("SUCCESS".equals(map.get("retcode").toUpperCase()) && "0000".equals(map.get("trxstatus"))) {
                    PPay pPayUpdate = new PPay();
                    pPayUpdate.setGuid(form.getPaymentId());
                    pPayUpdate.setUpdateDate(new Date());
                    pPayUpdate.setPayInfoUrl(map.get("payinfo"));//支付链接
                    pPayUpdate.setTrxid(map.get("trxid"));//通联唯一流水单号
                    pPayUpdate.setPayType(form.getpType());
                    pPayService.update(pPayUpdate);
                }else {
                    JSONObject Object = new JSONObject();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("paymentId", pPay.getGuid());
                    Object.put("errcode", map.get("trxstatus"));
                    Object.put("errmsg", map.get("errmsg"));
                    Object.put("data", jsonObject);
                    return Object;
                }
                JSONObject Object = new JSONObject();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("payinfo", map.get("payinfo"));
                jsonObject.put("paymentId", pPay.getGuid());
                jsonObject.put("trxid", map.get("trxid"));
                Object.put("errcode", "0000");
                Object.put("errmsg", "SUCCESS");
                Object.put("data", jsonObject);
                return Object;
            }else if("A01".equals(form.getpType())){
                logger.info("****************支付宝主扫******************");
                String BusinessType =  sCodeNameService.getNameByCode(pPay.getBusinessType());
                if(BusinessType==null||BusinessType==""){
                    BusinessType = pPay.getBusinessType();
                }
                //请求通联callout
                logger.info("***************************请求通联支付宝支付："+pPay.getPayAmount()+"*******>>>>>pPayCust："+pPayCust.getCustId());
                Map<String, String> map = callOut_tlPublicService.pay(pPay.getPayAmount(), TimeStamp, form.getpType(), BusinessType, pPay.getPayRemark(), "000000", constantConfig.getTlReturnURLMOREPLUS(),pPayCust);
                logger.info("***************************通联支付宝响应参数："+map.toString());
                //   Map<String, String> map = service.pay("1", TimeStamp, pType,pPay.getBusinessType(), pPay.getPayRemark(), "000000", FinalUtil.TL_RETURN_URL);
                //支付成功更新账单retcode：SUCCESS 请求成功 trxstatus：0000 拿到支付链接
                if ("SUCCESS".equals(map.get("retcode").toUpperCase()) && "0000".equals(map.get("trxstatus"))) {
                    PPay pPayUpdate = new PPay();
                    pPayUpdate.setGuid(form.getPaymentId());
                    pPayUpdate.setUpdateDate(new Date());
                    pPayUpdate.setPayInfoUrl(map.get("payinfo"));//支付链接
                    pPayUpdate.setTrxid(map.get("trxid"));//通联唯一流水单号
                    pPayUpdate.setPayType(form.getpType());
                    pPayService.update(pPayUpdate);
                }else {
                    JSONObject Object = new JSONObject();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("paymentId", pPay.getGuid());
                    Object.put("errcode", map.get("trxstatus"));
                    Object.put("errmsg", map.get("errmsg"));
                    Object.put("data", jsonObject);
                    return Object;
                }
                JSONObject Object = new JSONObject();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("payinfo", map.get("payinfo"));
                jsonObject.put("paymentId", pPay.getGuid());
                jsonObject.put("trxid", map.get("trxid"));
                Object.put("errcode", "0000");
                Object.put("errmsg", "SUCCESS");
                Object.put("data", jsonObject);
                return Object;
            }else{
                JSONObject Object = new JSONObject();
                Object.put("errcode", "1005");
                Object.put("errmsg", "无效的支付方式");
                return Object;
            }
        }
        return null;
    }
    /**微信小程序支付*/
    @RequestMapping(value = "/payByMiniApp", method = RequestMethod.POST)
    public Object payToTLByWEApp(@RequestBody CallOut_allinPayRequest form) throws Exception {
        logger.info("请求开始------------------");
        if (form.getPaymentId() != null && form.getPaymentId() !=""){
            String TimeStamp = String.valueOf(System.currentTimeMillis());//时间戳，用于商户交易订单号
            //根据guid查询数据库中的账单表
            PPay pPay = pPayService.getByKey(form.getPaymentId());
            logger.info(pPay+"支付信息----------------------");
            //根据小区sfid获取商户信息
            PPayCust pPayCust = getTLMessage(pPay.getEstateGuid(),form.getpType());
            logger.info(pPayCust.getCustId()+"商户Id----------------------");
            if ("W06".equals(form.getpType())){
                logger.info("****************微信小程序******************");
                String BusinessType =  sCodeNameService.getNameByCode(pPay.getBusinessType());
                if(BusinessType==null||BusinessType==""){
                    BusinessType = pPay.getBusinessType();
                }
                //请求通联callout
                logger.info("***************************请求通联微信小程序支付："+pPay.getPayAmount()+"*******>>>>>pPayCust："+pPayCust.getCustId());
                logger.info("***************************请求通联微信小程序支付：acct "+pPay.getAcct()+"*******>>>>>appid："+pPay.getSub_appid());
                Map<String, String> map = callOut_tlPublicService.payWechatApp(pPay.getPayAmount(), TimeStamp, form.getpType(), BusinessType, pPay.getPayRemark(), pPay.getAcct(),pPay.getSub_appid(), constantConfig.getTlReturnURLMOREPLUS(),pPayCust);
                logger.info("***************************通联微信小程序响应参数："+map.toString());
                //   Map<String, String> map = service.pay("1", TimeStamp, pType,pPay.getBusinessType(), pPay.getPayRemark(), "000000", FinalUtil.TL_RETURN_URL);
                //支付成功更新账单retcode：SUCCESS 请求成功 trxstatus：0000 拿到支付链接
                if ("SUCCESS".equals(map.get("retcode").toUpperCase()) && "0000".equals(map.get("trxstatus"))) {
                    PPay pPayUpdate = new PPay();
                    pPayUpdate.setGuid(form.getPaymentId());
                    pPayUpdate.setUpdateDate(new Date());
                    pPayUpdate.setPayInfoUrl(map.get("payinfo"));//支付链接
                    pPayUpdate.setTrxid(map.get("trxid"));//通联唯一流水单号
                    pPayUpdate.setPayType(form.getpType());
                    pPayService.update(pPayUpdate);
                }else {
                    JSONObject Object = new JSONObject();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("paymentId", pPay.getGuid());
                    Object.put("errcode", map.get("trxstatus"));
                    Object.put("errmsg", map.get("errmsg"));
                    Object.put("data", jsonObject);
                    return Object;
                }
                JSONObject Object = new JSONObject();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("payinfo", map.get("payinfo"));
                jsonObject.put("trxid", map.get("trxid"));
                jsonObject.put("paymentId", pPay.getGuid());
                Object.put("errcode", "0000");
                Object.put("errmsg", "SUCCESS");
                Object.put("data", jsonObject);
                return Object;
            }else{
                JSONObject Object = new JSONObject();
                Object.put("errcode", "1005");
                Object.put("errmsg", "无效的支付方式");
                return Object;
            }
        }
        return null;
    }
    /**微信公众号支付*/
    @RequestMapping(value = "/payByOfficialAccounts", method = RequestMethod.POST)
    public Object payToTLWeChatOfficialAccounts(@RequestBody CallOut_allinPayRequest form) throws Exception {
        logger.info("请求开始------------------");
        if (form.getPaymentId() != null && form.getPaymentId() !=""){
            String TimeStamp = String.valueOf(System.currentTimeMillis());//时间戳，用于商户交易订单号
            //根据guid查询数据库中的账单表
            PPay pPay = pPayService.getByKey(form.getPaymentId());
            logger.info(pPay+"支付信息----------------------");
            //根据小区sfid获取商户信息
            PPayCust pPayCust = getTLMessage(pPay.getEstateGuid(),form.getpType());
            logger.info(pPayCust.getCustId()+"商户Id----------------------");
            if ("W02".equals(form.getpType())){
                logger.info("****************微信公众号******************");
                String BusinessType =  sCodeNameService.getNameByCode(pPay.getBusinessType());
                if(BusinessType==null||BusinessType==""){
                    BusinessType = pPay.getBusinessType();
                }
                //请求通联callout
                logger.info("***************************请求通联微信公众号支付："+pPay.getPayAmount()+"*******>>>>>pPayCust："+pPayCust.getCustId());
                Map<String, String> map = callOut_tlPublicService.payWechatOfficialAccounts(pPay.getPayAmount(), TimeStamp, form.getpType(), BusinessType, pPay.getPayRemark(), "000000","", constantConfig.getTlReturnURLMOREPLUS(),pPayCust);
                logger.info("***************************通联微信微信公众号响应参数："+map.toString());
                //   Map<String, String> map = service.pay("1", TimeStamp, pType,pPay.getBusinessType(), pPay.getPayRemark(), "000000", FinalUtil.TL_RETURN_URL);
                //支付成功更新账单retcode：SUCCESS 请求成功 trxstatus：0000 拿到支付链接
                if ("SUCCESS".equals(map.get("retcode").toUpperCase()) && "0000".equals(map.get("trxstatus"))) {
                    PPay pPayUpdate = new PPay();
                    pPayUpdate.setGuid(form.getPaymentId());
                    pPayUpdate.setUpdateDate(new Date());
                    pPayUpdate.setPayInfoUrl(map.get("payinfo"));//支付链接
                    pPayUpdate.setTrxid(map.get("trxid"));//通联唯一流水单号
                    pPayUpdate.setPayType(form.getpType());
                    pPayService.update(pPayUpdate);
                }
                JSONObject Object = new JSONObject();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("payinfo", map.get("payinfo"));
                jsonObject.put("trxid", map.get("trxid"));
                jsonObject.put("paymentId", pPay.getGuid());
                Object.put("errcode", "0000");
                Object.put("errmsg", "SUCCESS");
                Object.put("data", jsonObject);
                return Object;
            }else{
                JSONObject Object = new JSONObject();
                Object.put("errcode", "1005");
                Object.put("errmsg", "无效的支付方式");
                return Object;
            }
        }
        return null;
    }

    /**
     * 根据小区sfid查询通联账户信息
     * @param estateGuid
     * @return
     */
    public PPayCust getTLMessage(String estateGuid ,String payType){
        return pPayCustService.getBySfGuid1(estateGuid,payType);
    }
}
